<template>
  <div class="blog-edit-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <h1>{{ isEditMode ? "编辑文章" : "文章详情" }}</h1>
      <div class="header-actions">
        <el-button
          v-if="isEditMode"
          type="info"
          @click="viewDetails"
          :icon="View"
        >
          查看详情
        </el-button>
        <el-button v-else type="primary" @click="editBlog" :icon="Edit">
          编辑文章
        </el-button>
        <el-button @click="goBack">返回列表</el-button>
      </div>
    </div>

    <!-- 编辑/详情表单 -->
    <el-card shadow="never" class="content-card">
      <el-form :model="blogForm" label-width="100px" style="max-width: 800px">
        <!-- 标题 -->
        <el-form-item label="文章标题">
          <el-input
            v-if="isEditMode"
            v-model="blogForm.title"
            placeholder="请输入文章标题"
            clearable
          />
          <div v-else class="view-content">{{ blogForm.title || "-" }}</div>
        </el-form-item>

        <!-- Slug -->
        <el-form-item label="Slug">
          <el-input
            v-if="isEditMode"
            v-model="blogForm.slug"
            placeholder="文章Slug"
            clearable
          />
          <div v-else class="view-content">{{ blogForm.slug || "-" }}</div>
        </el-form-item>

        <!-- 状态 -->
        <el-form-item label="状态">
          <el-select
            v-if="isEditMode"
            v-model="blogForm.status"
            placeholder="请选择状态"
          >
            <el-option label="已发布" value="published" />
            <el-option label="草稿" value="draft" />
            <el-option label="已归档" value="archived" />
            <el-option label="私有" value="private" />
          </el-select>
          <div v-else>
            <el-tag :type="getStatusType(blogForm.status)">
              {{ getStatusText(blogForm.status) }}
            </el-tag>
          </div>
        </el-form-item>

        <!-- 评论状态 -->
        <el-form-item label="评论状态">
          <el-switch
            v-if="isEditMode"
            v-model="blogForm.commentStatus"
            active-text="开启"
            inactive-text="关闭"
          />
          <div v-else>
            <el-tag :type="blogForm.commentStatus ? 'success' : 'danger'">
              {{ blogForm.commentStatus ? "评论开启" : "评论关闭" }}
            </el-tag>
          </div>
        </el-form-item>

        <!-- 置顶状态 -->
        <el-form-item label="置顶状态">
          <el-switch
            v-if="isEditMode"
            v-model="blogForm.isTop"
            active-text="置顶"
            inactive-text="普通"
          />
          <div v-else>
            <el-tag v-if="blogForm.isTop" type="warning">置顶</el-tag>
            <el-tag v-else type="info">普通</el-tag>
          </div>
        </el-form-item>

        <!-- 文章内容 -->
        <el-form-item label="文章内容">
          <el-input
            v-if="isEditMode"
            type="textarea"
            v-model="blogForm.content"
            :rows="12"
            placeholder="请输入文章内容"
            resize="none"
          />
          <div v-else class="content-view">
            <pre class="view-content">{{ blogForm.content || "暂无内容" }}</pre>
          </div>
        </el-form-item>

        <!-- 统计信息 -->
        <el-form-item label="统计信息" v-if="!isEditMode">
          <div class="stats-info">
            <span>浏览量: {{ blogForm.viewCount || 0 }}</span>
            <span style="margin-left: 20px"
              >点赞数: {{ blogForm.likeCount || 0 }}</span
            >
            <span style="margin-left: 20px"
              >字数: {{ blogForm.wordCount || 0 }}</span
            >
          </div>
        </el-form-item>

        <!-- 时间信息 -->
        <el-form-item label="时间信息" v-if="!isEditMode">
          <div class="time-info">
            <div>创建时间: {{ formatDate(blogForm.createdAt) }}</div>
            <div>更新时间: {{ formatDate(blogForm.updatedAt) }}</div>
            <div v-if="blogForm.publishedAt">
              发布时间: {{ formatDate(blogForm.publishedAt) }}
            </div>
          </div>
        </el-form-item>

        <!-- 操作按钮 -->
        <el-form-item>
          <el-button
            v-if="isEditMode"
            type="primary"
            @click="saveBlog"
            :loading="saving"
          >
            保存更改
          </el-button>
          <el-button @click="goBack">返回列表</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { Edit, View } from "@element-plus/icons-vue";
import axios from "axios";

const route = useRoute();
const router = useRouter();

// 响应式数据
const isEditMode = ref(true); // 默认编辑模式
const saving = ref(false);
const blogForm = reactive({
  id: null,
  title: "",
  slug: "",
  content: "",
  status: "draft",
  commentStatus: true,
  viewCount: 0,
  likeCount: 0,
  wordCount: 0,
  isTop: false,
  createdAt: "",
  updatedAt: "",
  publishedAt: "",
});

// 状态类型映射
const getStatusType = (status) => {
  const types = {
    published: "success",
    draft: "info",
    archived: "warning",
    private: "danger",
  };
  return types[status] || "info";
};

// 状态文本映射
const getStatusText = (status) => {
  const texts = {
    published: "已发布",
    draft: "草稿",
    archived: "已归档",
    private: "私有",
  };
  return texts[status] || "未知";
};

// 日期格式化
const formatDate = (dateString) => {
  if (!dateString) return "-";
  try {
    const date = new Date(dateString);
    return date.toLocaleString("zh-CN");
  } catch {
    return "-";
  }
};

// 加载博客数据
const loadBlog = async () => {
  try {
    const blogId = route.params.id;
    if (!blogId) {
      ElMessage.warning("文章ID不存在");
      return;
    }

    const response = await axios.get(`/api/blogs/${blogId}`);
    if (response.data.success) {
      Object.assign(blogForm, response.data.data);

      // 根据路由判断模式：编辑页面还是详情页面
      isEditMode.value = !route.path.includes("detail");
    } else {
      ElMessage.error("加载文章失败");
    }
  } catch (error) {
    console.error("加载文章失败:", error);
    ElMessage.error("加载文章失败");
  }
};

// 保存博客
const saveBlog = async () => {
  saving.value = true;
  try {
    if (blogForm.id) {
      await axios.put(`/api/blogs/${blogForm.id}`, blogForm);
      ElMessage.success("文章更新成功");

      // 保存成功后可以切换到详情模式
      // isEditMode.value = false;
      // 或者跳转到详情页面
      router.push(`/blog/detail/${blogForm.id}`);
    } else {
      await axios.post("/api/blogs", blogForm);
      ElMessage.success("文章创建成功");
      router.push("/blogs");
    }
  } catch (error) {
    console.error("保存失败:", error);
    ElMessage.error("保存失败");
  } finally {
    saving.value = false;
  }
};

// 查看详情 - 跳转到详情页面
const viewDetails = () => {
  router.push(`/blog/detail/${blogForm.id}`);
};

// 编辑文章 - 切换到编辑模式或跳转到编辑页面
const editBlog = () => {
  router.push(`/blog/edit/${blogForm.id}`);
};

// 返回列表
const goBack = () => {
  router.push("/blogs");
};

// 初始化
onMounted(() => {
  loadBlog();
});
</script>

<style scoped>
.blog-edit-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #ebeef5;
}

.page-header h1 {
  margin: 0;
  color: #303133;
  font-size: 24px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.content-card {
  margin-top: 20px;
}

.view-content {
  padding: 8px 0;
  color: #606266;
  line-height: 1.6;
}

.content-view {
  background: #fafafa;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 16px;
  min-height: 200px;
}

.content-view pre {
  white-space: pre-wrap;
  word-break: break-word;
  margin: 0;
  font-family: inherit;
}

.stats-info {
  color: #606266;
  font-size: 14px;
}

.time-info {
  color: #606266;
  font-size: 14px;
  line-height: 1.8;
}

.time-info div {
  margin-bottom: 4px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .blog-edit-container {
    padding: 12px;
  }

  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .header-actions {
    width: 100%;
    justify-content: flex-end;
  }
}
</style>
